/**
 * 开源版本请务必保留此注释头信息，若删除捷码开源〔GEMOS〕官方保留所有法律责任追究！
 * 本软件受国家版权局知识产权以及国家计算机软件著作权保护（登记号：2018SR503328）
 * 不得恶意分享产品源代码、二次转售等，违者必究。
 * Copyright (c) 2020 gemframework all rights reserved.
 * http://www.gemframework.com
 * 版权所有，侵权必究！
 */
package com.gemframework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gemframework.common.exception.GemException;
import com.gemframework.common.utils.GemRedisUtils;
import com.gemframework.common.utils.security.GemPasswordUtils;
import com.gemframework.mapper.MemberMapper;
import com.gemframework.model.common.ApiToken;
import com.gemframework.model.common.SaltPassword;
import com.gemframework.model.entity.po.Member;
import com.gemframework.model.enums.ExceptionCode;
import com.gemframework.model.response.AccessTokenResponse;
import com.gemframework.model.response.RefreshTokenResponse;
import com.gemframework.service.MemberService;
import com.gemframework.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.gemframework.common.utils.GemCacheUtils.getAccessTokenKeyByMemberId;

@Slf4j
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    GemRedisUtils gemRedisUtils;

    @Autowired
    TokenService tokenService;

    @Override
    public boolean exits(Member entity) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name",entity.getAccount());
        //编辑
        if(entity.getId() != null && entity.getId() !=0){
            queryWrapper.and(wrapper -> wrapper.ne("id",entity.getId()));
        }
        if(count(queryWrapper)>0){
            return true;
        }
        return false;
    }


    @Override
    public AccessTokenResponse getAccessTokenByAccount(String account,String password) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account",account);
        Member member = getOne(queryWrapper);
        //查询用户
        if(member==null || member.getId() == null){
            throw new GemException(ExceptionCode.MEMBER_NOT_EXIST);
        }
        //验证密码
        if(!GemPasswordUtils.validatePassword(password,member.getPassword(),member.getSalt())){
            throw new GemException(ExceptionCode.MEMBER_AUTHENTICATION_FAILED);
        }
        //获取token
        ApiToken token = tokenService.getAccessToken(member.getId());
        AccessTokenResponse resp = AccessTokenResponse.builder()
                .accessToken(token.getAccessToken())
                .expiresIn(token.getAccessTokenExpireTime().getTime()/1000-new Date().getTime()/1000)
                .refreshToken(token.getRefreshToken())
                .member(member)
                .build();
        return resp;
    }

    @Override
    public RefreshTokenResponse refreshAccessToken(Long memberId, String refreshToken) {
        Member member = getById(memberId);
        //查询用户
        if(member==null || member.getId() == null){
            throw new GemException(ExceptionCode.MEMBER_NOT_EXIST);
        }
        ApiToken token = tokenService.refreshToken(memberId,refreshToken);
        RefreshTokenResponse resp = RefreshTokenResponse.builder()
                .accessToken(token.getAccessToken())
                .expiresIn(token.getAccessTokenExpireTime().getTime()/1000-new Date().getTime()/1000)
                .refreshToken(token.getRefreshToken())
                .build();
        return resp;
    }

    @Override
    public void setPassword(Long memberId, String password) {
        SaltPassword saltPassword = GemPasswordUtils.saltPassword(password);
        Member member = new Member();
        member.setId(memberId);
        member.setSalt(saltPassword.getSalt());
        member.setPassword(saltPassword.getPassword());
        this.updateById(member);
    }
}